package com.ruoyi.meterManager.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CbConstans;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.meterManager.domain.Custinfo;
import com.ruoyi.meterManager.domain.MeterPicture;
import com.ruoyi.meterManager.domain.Meterread;
import com.ruoyi.meterManager.domain.requestDto.AlterBIRequestDto;
import com.ruoyi.meterManager.domain.requestDto.BaseQueryDto;
import com.ruoyi.meterManager.domain.requestDto.UpdateMrEntity;
import com.ruoyi.meterManager.domain.responseDto.MeterPayHis;
import com.ruoyi.meterManager.domain.responseDto.UmResponseDto;
import com.ruoyi.meterManager.domain.responseDto.MeterCbHis;
import com.ruoyi.meterManager.domain.responseDto.MeterCursor;
import com.ruoyi.meterManager.mapper.CustinfoMapper;
import com.ruoyi.meterManager.mapper.MeterPictureMapper;
import com.ruoyi.meterManager.mapper.MeterreadMapper;
import com.ruoyi.meterManager.service.MeterreadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: ruoyi
 * @description: 抄表库（表册）服务
 * @author: Chenhenan
 * @create: 2021-07-22 13:20
 **/
@Service
public class MeterreadServiceImpl implements MeterreadService {

    @Autowired
    private MeterreadMapper meterreadMapper;

    @Autowired
    private MeterPictureMapper pictureMapper;

    @Autowired
    private CustinfoMapper custinfoMapper;

    @Value("${meter.telephone}")
    private String telephone;

    @Value("${meter.printinfo}")
    private String printinfo;

    @Value("${img_ip}")
    private String IMG_IP;

    /**
     * 查询表计划列表（无余额/欠费条件）
     * @param baseQueryDto
     * @return
     */
    @Override
    public List<Map> selectBaseInfo(BaseQueryDto baseQueryDto) {
        if(StringUtils.isEmpty(baseQueryDto.getBfrper())){
            throw new CustomException("抄表员id为空！");
        }
        if(StringUtils.isEmpty(baseQueryDto.getType())){
            throw new CustomException("分类不能为空");
        }

        // 如果是全部tab查询（查询表工负责所有水表户）
        if(CbConstans.TYPE_ONHAND.equals(baseQueryDto.getType())||CbConstans.TYPE_ALL.equals(baseQueryDto.getType())){
            if("mrrdate".equals(baseQueryDto.getOrderByColumn())){
                throw new CustomException("排序字段有误，查询非已抄不可按抄表日期排序");
            }
        }
        //查询全部用户信息
        if(CbConstans.TYPE_ALL.equals(baseQueryDto.getType())){
            return meterreadMapper.selectMeterInfo(baseQueryDto);
            //查询表计划信息
        }else {
            List<Map> maps = meterreadMapper.selectBaseMeterReadInfo(baseQueryDto);
            if(maps.size() == 1){
                Map map = maps.get(0);
                if(map.size() == 1){
                    return new ArrayList<>();
                }
            }
            return maps;
        }
    }

    /**
     * 查询表计划列表(带余额条件)
     * @param baseQueryDto
     * @return
     */
    @Override
    public Map selectBaseInfo1(BaseQueryDto baseQueryDto) {
        if(StringUtils.isEmpty(baseQueryDto.getBfrper())){
            throw new CustomException("抄表员id为空！");
        }
        if(StringUtils.isEmpty(baseQueryDto.getType())){
            throw new CustomException("分类不能为空");
        }

        // 如果是全部tab查询（查询表工负责所有水表户）
        if(CbConstans.TYPE_ONHAND.equals(baseQueryDto.getType())||CbConstans.TYPE_ALL.equals(baseQueryDto.getType())){
            if("mrrdate".equals(baseQueryDto.getOrderByColumn())){
                throw new CustomException("排序字段有误，查询全部不可按抄表日期排序");
            }
        }

        Integer pageNum = baseQueryDto.getPageNum();
        Integer pageSize = baseQueryDto.getPageSize();
        baseQueryDto.setStart((pageNum-1)*pageSize + 1);
        baseQueryDto.setEnd(pageNum*pageSize);
        baseQueryDto.setPageSize(null);
        baseQueryDto.setPageNum(null);

        //查询全部用户信息
        if(CbConstans.TYPE_ALL.equals(baseQueryDto.getType())){

            Map m = new HashMap();
            List<Map> rows = meterreadMapper.selectMeterInfo(baseQueryDto);
            m.put("rows",rows);
            int totalCounts = meterreadMapper.selectMeterInfoCounts(baseQueryDto);
            m.put("counts",totalCounts);
            return m;
            //查询表计划信息
        }else {
            Map m = new HashMap();
            List<Map> rows = meterreadMapper.selectBaseMeterReadInfo(baseQueryDto);
            m.put("rows",rows);
            int totalCounts = meterreadMapper.selectBaseMeterReadInfoCounts(baseQueryDto);
            m.put("counts",totalCounts);
            return m;
        }
    }

    /**
     * 查询表计划详情（单个）
     * @param baseQueryDto
     * @return
     */
    @Override
    public MeterCursor selectDetailByMrId(BaseQueryDto baseQueryDto) {
        if(StringUtils.isEmpty(baseQueryDto.getBfrper())){
            throw new CustomException("抄表员id为空！");
        }
        if(StringUtils.isEmpty(baseQueryDto.getMiid())){
            throw new CustomException("水表编号/用户编号为空！");
        }
        Map<String,String> otherMeter = new HashMap();
        //查询前后
        /*if(!"0".equals(baseQueryDto.getQueryRule()) && baseQueryDto.getQueryRule() != null){
            otherMeter = meterreadMapper.getOtherMeter(baseQueryDto);
            //查询前一条
            if("1".equals(baseQueryDto.getQueryRule())){
                String previousmeter = otherMeter.get("PREVIOUSMETER");
                baseQueryDto.setMiid(previousmeter);
                //查询后一条
            }else{
                String nextmeter = otherMeter.get("NEXTMETER");
                baseQueryDto.setMiid(nextmeter);
            }
        }*/


        Map param = new HashMap();
        param.put("P_BFRPER",baseQueryDto.getBfrper());
        param.put("P_MIID",baseQueryDto.getMiid());
        MeterCursor mc = meterreadMapper.selectDetailByMrId(param);
        //List<MeterCursor> o_cursor = (List<MeterCursor>) param.get("c");
        if(mc == null){
            return null;
        }

        //如果miclass为空，将值设为“0”，代表非级别表
        if(StringUtils.isBlank(mc.getMiclass())){
            mc.setMiclass(CbConstans.NO_TABLE);
        }

        // 年阶梯累计水量 未抄的水表，需要通过查询reclist表查询
        if("N".equals(mc.getHandlestatus())){
            String micode = mc.getMicode();
            int yearStepSL = meterreadMapper.getYearStepSL(micode);
            mc.setNjtljsl(yearStepSL + "");
        }

        //（原总分表）如果不是普通表（多级表）且不是末级表
        if((!CbConstans.NO_TABLE.equals(mc.getMiclass())) && (!"Y".equals(mc.getMiflag()))){
            List<Map> zfChild = meterreadMapper.selectZFChild(mc.getMiid());
            mc.setZfChilds(zfChild);
            // 获取分表允许最小抄表指针
            int minsl = this.getminsl(mc.getMiid(), mc.getMrscode());
            mc.setMinsl(minsl);
            /*int minsl = 0;
            Integer fbsum = meterreadMapper.getFenMrsl(mc.getMiid());
            if(fbsum == null ){
                fbsum = 0;
            }
            minsl = mc.getMrscode() + fbsum;
            mc.setMinsl(minsl);
            // 当前表水量 = meterread.mrsl - （多级表）子孙表水量
            int thisMrsl = Integer.valueOf(mc.getMrsl()) - fbsum;
            mc.setMrsl(thisMrsl+"");*/
        }
        //（原合收表）如果当前是一户多表
        if(CbConstans.HS_TABLE.equals(mc.getMipriflag())){
            //当前是主表
            if(mc.getMiid().equals(mc.getMicode())){
                List<Map> hsChilds = meterreadMapper.selectHSChild(mc.getMiid());
                mc.setHsChilds(hsChilds);
            }
        }
        //动态获取营业分公司电话
        String phoneNum = meterreadMapper.getPhoneNum(baseQueryDto.getBfrper());
        if(phoneNum != null){
            String[] split = phoneNum.split("-");
            phoneNum = "、" + split[split.length-1];
        }

        otherMeter = meterreadMapper.getOtherMeter(baseQueryDto);

        if(otherMeter != null){
            mc.setPreviousmeter(otherMeter.get("PREVIOUSMETER"));
            mc.setNextmeter(otherMeter.get("NEXTMETER"));
        }

        mc.setTelephone(telephone + phoneNum);
        mc.setPrintInfo(printinfo);
        return mc;
    }




    @Override
    public List<MeterCursor> selectDetails(String oaid) {


        List<MeterCursor> o_cursor = meterreadMapper.selectCursor(oaid);
        //List<MeterCursor> o_cursor = (List<MeterCursor>) param.get("c");
        if(o_cursor.size()==0){
            return null;
        }
        for(MeterCursor mc: o_cursor){
            /*//如果当前是总分表的主表
            if(CbConstans.MAIN_TABLE.equals(mc.getMiclass())){
                List<Map> zfChild = meterreadMapper.selectZFChild(mc.getMiid());
                mc.setZfChilds(zfChild);
            }
            //如果当前是合收表
            if(CbConstans.HS_TABLE.equals(mc.getMipriflag())){
                //当前是主表
                if(mc.getMiid().equals(mc.getMipriid())){
                    List<Map> hsChilds = meterreadMapper.selectHSChild(mc.getMiid());
                    mc.setHsChilds(hsChilds);
                }
            }*/


            //如果miclass为空，将值设为“0”，代表非级别表
            if(StringUtils.isBlank(mc.getMiclass())){
                mc.setMiclass(CbConstans.NO_TABLE);
            }

            //（原总分表）如果不是普通表（多级表）且不是末级表
            if((!CbConstans.NO_TABLE.equals(mc.getMiclass())) && (!"Y".equals(mc.getMiflag()))){
                List<Map> zfChild = meterreadMapper.selectZFChild(mc.getMiid());
                mc.setZfChilds(zfChild);
                // 获取分表允许最小抄表指针
                int minsl = this.getminsl(mc.getMiid(), mc.getMrscode());
                mc.setMinsl(minsl);
                /*int minsl = 0;
                Integer fbsum = meterreadMapper.getFenMrsl(mc.getMiid());
                if(fbsum == null ){
                    fbsum = 0;
                }
                minsl = mc.getMrscode() + fbsum;
                mc.setMinsl(minsl);
                // 当前表水量 = meterread.mrsl - （多级表）子孙表水量
                int thisMrsl = Integer.valueOf(mc.getMrsl()) - fbsum;
                mc.setMrsl(thisMrsl+"");*/
            }
            //（原合收表）如果当前是一户多表
            if(CbConstans.HS_TABLE.equals(mc.getMipriflag())){
                //当前是主表
                if(mc.getMiid().equals(mc.getMicode())){
                    List<Map> hsChilds = meterreadMapper.selectHSChild(mc.getMiid());
                    mc.setHsChilds(hsChilds);
                }
            }
        }
        //动态获取营业分公司电话
        String phoneNum = meterreadMapper.getPhoneNum(oaid);
        if(phoneNum != null){
            String[] split = phoneNum.split("-");
            phoneNum = "、" + split[split.length-1];
        }

        o_cursor.get(0).setTelephone(telephone + phoneNum);
        o_cursor.get(0).setPrintInfo(printinfo);

        return o_cursor;
    }

    @Override
    public List<MeterCursor> selectDetailsByCondition(BaseQueryDto baseQueryDto) {
        Map param = new HashMap();
        param.put("I_BFRPER",baseQueryDto.getBfrper());
        param.put("BFID",baseQueryDto.getBfid());
        param.put("BALANCE",baseQueryDto.getBalance());
        param.put("KEYWORD",baseQueryDto.getKeyWord());
        meterreadMapper.selectCursor(baseQueryDto.getBfrper());
        List<MeterCursor> o_cursor = (List<MeterCursor>) param.get("c");
        if(o_cursor.size()==0){
            return null;
        }
        for(MeterCursor mc: o_cursor){
            //如果当前是总分表的主表
            if(CbConstans.MAIN_TABLE.equals(mc.getMiclass())){
                List<Map> zfChild = meterreadMapper.selectZFChild(mc.getMiid());
                mc.setZfChilds(zfChild);
            }
            //如果当前是合收表
            if(CbConstans.HS_TABLE.equals(mc.getMipriflag())){
                //当前是主表
                if(mc.getMiid().equals(mc.getMipriid())){
                    List<Map> hsChilds = meterreadMapper.selectHSChild(mc.getMiid());
                    mc.setHsChilds(hsChilds);
                }
            }
        }
        return o_cursor;
    }

    /**
     * 查询表册列表
     * @param baseQueryDto
     * @return
     */
    @Override
    public List<String> selectBF(BaseQueryDto baseQueryDto) {
        if(StringUtils.isEmpty(baseQueryDto.getBfrper())){
            throw new CustomException("抄表员id为空！");
        }
        if(StringUtils.isEmpty(baseQueryDto.getType())){
            throw new CustomException("分类不能为空");
        }

        // 如果是全部tab查询（查询表工负责所有水表户）
        if(CbConstans.TYPE_ALL.equals(baseQueryDto.getType())){
            return meterreadMapper.selectBF(baseQueryDto);
        }else{
            return meterreadMapper.selectMrBF(baseQueryDto);
        }

    }


    /**
     * 上传数据更新指针、照片
     * @param updateMrEntity
     * @return
     */
    @Override
    @Transactional
    public UmResponseDto updateMeter(MultipartFile[] file, UpdateMrEntity updateMrEntity, LoginUser loginUser) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        int actualMaximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //如果当前是本月最后一天
        if(dayOfMonth == actualMaximum){
            throw new CustomException("本月最后一天不可抄表！");
        }
        //如果当前是本月第一天
        if(dayOfMonth == 1){
            //获取当前小时
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            //如果是3点钱
            if(hour < 3){
                throw new CustomException("每月第一天3点前不可抄表！");
            }
        }

        Boolean fileExist = file != null && file.length > 0;
        if(StringUtils.isEmpty(updateMrEntity.getBfrper())){
            throw new CustomException("抄表员id为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getMiid())){
            throw new CustomException("水表编号/用户编号为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getBk())){
            throw new CustomException("表况为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getEcode())){
            throw new CustomException("抄见止码为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getMonth())){
            throw new CustomException("抄表月份为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getMemo())){
            updateMrEntity.setMemo("NNUULL");
        }
        if(StringUtils.isEmpty(updateMrEntity.getMrifgu())){
            throw new CustomException("示数来源为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getMrrdate())){
            throw new CustomException("抄表日期为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getMrreadokpz())){
            throw new CustomException("照片更新审核标识为空！");
        }
        if((fileExist && "N".equals(updateMrEntity.getMrreadokpz()))
                || (!fileExist && "Y".equals(updateMrEntity.getMrreadokpz()))){
            throw new CustomException("照片更新审核标识有误！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getI_seq())){
            throw new CustomException("流水号为空！");
        }
        String oaname = loginUser.getUser().getUserName();//表工名称
        String miid = updateMrEntity.getMiid();//水表编号
        String oaid = loginUser.getUser().getLoginName();//表工号

        //上传照片
        List<MeterPicture> pictureList = new ArrayList<>();

        String mrreadok = meterreadMapper.selectMrreadok(updateMrEntity.getMiid());

        if(CbConstans.mrreadok_Y.equals(mrreadok)||CbConstans.mrreadok_X.equals(mrreadok)){
            throw new CustomException("该水表已抄，请勿重复提交！");
        }

        try
        {
            //"\上传图片日期\抄表员\表编号_拍照时间精确到秒"
            //"\2021-08-14\牛夯\102431187_20210814142208.jpg"
            if(fileExist){
                //String userBranch = operaccntMapper.getUserBranch(oaid);
                Map<String,String> printInfo = meterreadMapper.getImgPrintInfo(miid);
                printInfo.put("oaname",oaname);
                printInfo.put("miid",miid);
                printInfo.put("workPosition",updateMrEntity.getWorkPosition());
                // 上传文件路径 E:/凯纳科技/抄表APP/uploadPath/upload
                String filePath = RuoYiConfig.getUploadPath() + printInfo.get("mismfid");
                for (int i = 0; i < file.length; i++) {
                    // 上传并返回新文件名称 "\2021-08-14\牛夯\102431187_20210814142208.jpg"
                    String pmpath =
                            FileUploadUtils
                                    .uploadMeterImg(filePath,file[i],printInfo,i);
                    //String url = filePath.replace(File.separator,"//");
                    String url = filePath + pmpath;
                    MeterPicture picture = new MeterPicture();
                    picture.setMpmiid(miid);
                    picture.setPmsize(file[i].getSize());
                    picture.setPmpath(pmpath);
                    picture.setPmtime(new Date());
                    picture.setPmbz("1"); // 1.抄表图片，2.用户巡检图片，3.用户基础信息修改
                    picture.setPmper(oaid);
                    picture.setPmpname(oaname);
                    picture.setCiid(miid);
                    picture.setPmfactPath(url);
                    pictureList.add(picture);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new CustomException("照片上传失败！");
        }

        // 调用上传存储过程
        meterreadMapper.updateMeter(updateMrEntity);
        UmResponseDto umResponseDto = new UmResponseDto();
        // |000|08003|0000001400|0000003360|0000001330|0000000000|0000004690|+0000029075|+0000024385|+0000000240|+0000000095
        String o_out_trans = updateMrEntity.getO_out_trans();
        o_out_trans = o_out_trans.substring(1);
        String[] split = o_out_trans.split("\\|");
        // 数据修改失败
        if("999".equals(split[0])){
            //this.deletePicture(mpmiid);
            throw new CustomException(split[2]);
        }
        if("222".equals(split[0]) || "333".equals(split[0])){
            //this.deletePicture(mpmiid);
            //throw new CustomException(split[2]);
        }
        for(MeterPicture pic: pictureList){
            pictureMapper.insertPicture(pic);
        }
        umResponseDto.setCode(split[0]);
        if("000".equals(split[0]) && split.length == 11){
            umResponseDto.setType(split[1]);
            umResponseDto.setRecsl(Integer.valueOf(split[2])/100);
            umResponseDto.setSje(new BigDecimal(split[3]));
            umResponseDto.setWsje(new BigDecimal(split[4]));
            umResponseDto.setFjf(new BigDecimal(split[5]));
            umResponseDto.setRecje(new BigDecimal(split[6]));
            umResponseDto.setLasttimepremoney(new BigDecimal(split[7]));
            umResponseDto.setThistimepremoney(new BigDecimal(split[8]));
            umResponseDto.setSfprice(new BigDecimal(split[9]));
            umResponseDto.setWsfprice(new BigDecimal(split[10]));
        }
        String sl = null;
        //总表水量
        Integer zmrsl = meterreadMapper.getMrsl(miid);
        //分表水量
        Integer fmrsl = meterreadMapper.getFenMrsl(miid);

        // 正常情况下 返回水量 = 总表-分表量
        if("000".equals(umResponseDto.getCode())){
            //如果没有分表水量
            if(fmrsl == null){
                sl = zmrsl+"";
            }else {//如果分表有水量
                sl = zmrsl - fmrsl + "";
            }
        }else{
            sl = "0";
        }

        /*String bk = "BK_" + updateMrEntity.getBk();
        String bk_z = CbConstans.BK_XF.get(bk);


        // 正常情况下 返回水量 = 总表-分表量
        if("000".equals(umResponseDto.getCode())){
            //如果没有分表水量
            if(fmrsl == null){
                sl = zmrsl+"";
            }else {//如果分表有水量
                sl = zmrsl - fmrsl + "";
            }
        // 总表或分表有表异常
        }else{

            //表异常
            if("0".equals(updateMrEntity.getEcode()) && CbConstans.BK_Z02.equals(bk_z)){
                sl = "0";
            //其他异常
            }else{
                sl = zmrsl + "";
            }
        }*/

        umResponseDto.setMrsl(sl);
        return umResponseDto;
    }

    /**
     * 查询抄表历史记录
     * @param baseQueryDto
     * @return
     */
    @Override
    public List<MeterCbHis> selectCbHistory(BaseQueryDto baseQueryDto) {
        if(StringUtils.isEmpty(baseQueryDto.getBfrper())){
            throw new CustomException("抄表员id为空！");
        }
        if(StringUtils.isEmpty(baseQueryDto.getMiid())){
            throw new CustomException("水表编号/用户编号为空！");
        }
        Map param = new HashMap();
        param.put("P_BFRPER",baseQueryDto.getBfrper());
        param.put("P_MIID",baseQueryDto.getMiid());
        List<MeterCbHis> meterCbHis = meterreadMapper.selectCbHistory(param);
        return meterCbHis;
    }


    /**
     * 查询缴费历史记录
     * @param baseQueryDto
     * @return
     */
    @Override
    public List<MeterPayHis> selectPayHistory(BaseQueryDto baseQueryDto) {
        if(StringUtils.isEmpty(baseQueryDto.getBfrper())){
            throw new CustomException("抄表员为空");
        }
        if(StringUtils.isEmpty(baseQueryDto.getMiid())){
            throw new CustomException("水表编号/用户编号为空！");
        }
        Map param = new HashMap();
        param.put("P_BFRPER",baseQueryDto.getBfrper());
        param.put("P_MIID",baseQueryDto.getMiid());
        List<MeterPayHis> meterPayHis = meterreadMapper.selectPayHistory(param);
        return meterPayHis;
    }

    /**
     * 删除图片记录
     * @param miid
     */
    @Override
    public void deletePicture(String miid) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,1);
        Date time = calendar.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start = sf.format(time);

        Calendar max = Calendar.getInstance();
        max.setTime(new Date());
        max.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        max.set(Calendar.HOUR_OF_DAY,23);
        max.set(Calendar.MINUTE,59);
        max.set(Calendar.SECOND,59);
        Date time1 = max.getTime();
        String end = sf.format(time1);

        Map map = new HashMap();
        map.put("start",start);
        map.put("end",end);
        map.put("mpmiid",miid);

        pictureMapper.deletePictureByMiid(map);
    }

    /**
     * 退审
     * @param updateMrEntity
     * @return
     */
    @Override
    public String cancelReview(UpdateMrEntity updateMrEntity) {
        if(StringUtils.isEmpty(updateMrEntity.getMiid())){
            throw new CustomException("用户编号为空！");
        }
        if(StringUtils.isEmpty(updateMrEntity.getI_seq())){
            throw new CustomException("流水号为空！");
        }
        Map param = new HashMap();
        param.put("i_in_trans",updateMrEntity.getMiid());
        param.put("i_SEQ",updateMrEntity.getI_seq());
        param.put("o_out_trans", new String());
        meterreadMapper.cancelReview(param);
        String o_out_trans = (String)param.get("o_out_trans");
        o_out_trans = o_out_trans.substring(1);
        String[] split = o_out_trans.split("\\|");
        // 退审失败
        if("999".equals(split[0])){
            throw new CustomException(split[2]);
        }
        return "退审成功！";
    }

    @Override
    public String alterBaseInfo(AlterBIRequestDto alterBIRequestDto) {

        if(StringUtils.isBlank(alterBIRequestDto.getApplyflag())){
            throw new CustomException("申请状态不能为空！");
        }
        if(StringUtils.isBlank(alterBIRequestDto.getUserno())){
            throw new CustomException("用户编号不能为空！");
        }
        if(StringUtils.isBlank(alterBIRequestDto.getCoperno())){
            throw new CustomException("抄表员编号不能为空！");
        }

//        Map param = new HashMap();
//        param.put("V_USER_NO",alterBIRequestDto.getUserno());
//        param.put("V_LINK_MAN",alterBIRequestDto.getLinkman());
//        param.put("V_CONNECT_PHONE",alterBIRequestDto.getConnectphone());
//        param.put("V_COPER_NO",alterBIRequestDto.getUserno());
//        param.put("V_apply_flag",alterBIRequestDto.getUserno());
//        param.put("V_CBBZ",alterBIRequestDto.getCbbz());
//        param.put("V_USERNm",alterBIRequestDto.getUsername());
//        param.put("v_MIPFID",alterBIRequestDto.getMipfid());
//        param.put("v_MDCALIBER",alterBIRequestDto.getMdcaliber());
//        param.put("v_MDNO",alterBIRequestDto.getMdno());
//        param.put("v_DQGFH",alterBIRequestDto.getDqgfh());
//        param.put("v_DQSFH",alterBIRequestDto.getDqsfh());
//        param.put("v_qfh",alterBIRequestDto.getQfh());
//        param.put("v_JCGFH",alterBIRequestDto.getJcgfh());
//        param.put("V_apply_flag",alterBIRequestDto.getApplyflag());
//        param.put("v_MISIDE",alterBIRequestDto.getMiside());
//        param.put("i_SEQ",alterBIRequestDto.getI_seq());
//        param.put("o_out_trans", new String());



        return null;
    }

    @Override
    public Boolean getFenStatus(String mid) {
        int result = meterreadMapper.getFenStatus(mid);
        if(result > 0){
            return false;
        }
        return true;
    }

    @Override
    public String getPictureMonth(String oaid) {
        return meterreadMapper.getPictureMonth(oaid);
    }

    @Override
    public int updateMeterread(Meterread meterread) {
        return meterreadMapper.updateMeterread(meterread);
    }

    @Override
    public int updateCustinfo(Custinfo custinfo) {
        return custinfoMapper.updateCustinfo(custinfo);
    }

    /**
     * 获取自抄表用户信息
     * @param baseQueryDto
     * @return
     */
    @Override
    public List<Map> getZcbList(BaseQueryDto baseQueryDto) {
        List<Map> list = new ArrayList<>();
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        int actualMaximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //如果当前是本月最后一天
        if(dayOfMonth == actualMaximum){
            return list;
        }
        list = pictureMapper.getZcbList(baseQueryDto);
        return list;
    }

    @Override
    public Map getZcbDetail(BaseQueryDto baseQueryDto) {

        String cbPre = "";
        String zcbPre = "zcbfile/";

        if(baseQueryDto.getBfrper() == null){
            throw new CustomException("认证失败！", HttpStatus.UNAUTHORIZED);
        }
        if(baseQueryDto.getMiid() == null){
            throw new CustomException("用户编号/水表编号不能为空");
        }
        Map detail = pictureMapper.getZcbDetail(baseQueryDto);
        List<Map> pictures = pictureMapper.getZcbDetailPicture(baseQueryDto);
        String pmpath = IMG_IP + zcbPre + detail.get("MISMFID")+detail.get("PMPATH");
        if(StringUtils.isNotBlank((String)detail.get("PMPATH"))){
            pmpath = IMG_IP + zcbPre + detail.get("MISMFID")+detail.get("PMPATH");
        }
        String prepath = null;
        String mismfid = (String)detail.get("MISMFID");
        if(pictures != null && pictures.size() != 0){
            for(int i = 0; i < pictures.size(); i++){
                if(StringUtils.isNotBlank((String)pictures.get(i).get("PREPATH"))){
                    if("4".equals(pictures.get(i).get("pmbz"))){
                        prepath = IMG_IP + cbPre + mismfid + pictures.get(i).get("PREPATH");
                        pictures.get(i).put("prepath",prepath);
                    }else {
                        prepath = IMG_IP + zcbPre + mismfid + pictures.get(i).get("PREPATH");
                        pictures.get(i).put("prepath",prepath);
                    }
                }

            }
        }

        /*if(StringUtils.isNotBlank((String)detail.get("PREPATH"))){
            // 自抄表
            if("8".equals(detail.get("MRDATASOURCE"))){
                prepath = IMG_IP + "img/" + detail.get("MISMFID")+detail.get("PREPATH");
                // 手机抄表
            }else if("9".equals(detail.get("MRDATASOURCE"))){
                prepath = IMG_IP + "sjcb/" + detail.get("MISMFID")+detail.get("PREPATH");
            }
        }*/

        detail.put("PMPATH",pmpath);
        detail.put("PREPATH",pictures);
        //detail.put("PREPATH",prepath);

        String zcbmemo = (String)detail.get("ZCBMEMO");
        String flag = (String)detail.get("FLAG");

        if(StringUtils.isNotBlank(zcbmemo)){
            String memo = null;
            //营收端退审
            if("4".equals(flag)){
                memo  = pictureMapper.getZcbRefuseReason(zcbmemo,"zcb_yx");
            }else if("2".equals(flag)){
                memo = pictureMapper.getZcbRefuseReason(zcbmemo,"zcb_cby");
            }

            detail.put("ZCBMEMO",memo);
        }

        return detail;
    }

    @Override
    public List<Map> getZcbRefuseReasonList() {
        List<Map> zcbRefuseReason = pictureMapper.getZcbRefuseReasonList();
        return zcbRefuseReason;
    }

    @Override
    public void checkZcb(MeterPicture picture) {
        if(StringUtils.isBlank(picture.getMpmiid())){
            throw new CustomException("水表编号不能为空");
        }
        if(StringUtils.isBlank(picture.getFlag())){
            throw new CustomException("审核标识不能为空");
        }
        if("1".equals(picture.getFlag()) && StringUtils.isBlank(picture.getPmper())){
            throw new CustomException("审核通过必须上传指针");
        }
        if(!"1".equals(picture.getFlag()) && !"2".equals(picture.getFlag())){
            throw new CustomException("手机审核标识有误");
        }
        if("2".equals(picture.getFlag()) && StringUtils.isBlank(picture.getZcbmemo())){
            throw new CustomException("审核未通过时退审理由不能为空");
        }
        //如果是手机审核通过，需要将退审原因设为空
        if("1".equals(picture.getFlag())){
            picture.setZcbmemo("");
        }
        pictureMapper.checkZcb(picture);
    }
    /**
     * 获取分表允许最小抄表指针
     * @param zid
     * @param mrscode
     * @return
     */
    private int getminsl(String zid,int mrscode) {

/*        int fenStatus = meterreadMapper.getFenStatus(zid);
        if(fenStatus > 0){
            return 0;
        }*/
        //获取分表总水量
        Integer fbsum = meterreadMapper.getFenMrsl(zid);
        if(fbsum == null ){
            fbsum = 0;
        }
        return mrscode + fbsum;
    }


    /** 获取服务器前缀 http://localhost:8090 */
    private String getUrl()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    /** 转换金额格式 */
    private BigDecimal getBDValue(String val){
        if(StringUtils.isBlank(val)){
            val = "0";
        }
        BigDecimal bigDecimal = new BigDecimal(val);
        BigDecimal bValue = bigDecimal.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UNNECESSARY);
        return bValue;
    }







}